<?php

namespace App\Jobs;

use App\Dictionary;
use App\Model\User;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class SaveWechatUser implements ShouldQueue
{
    use InteractsWithQueue, Queueable, SerializesModels;

    protected $info;

    protected $subscribed_at;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($info)
    {
        $this->info = $info;

        $this->subscribed_at = Carbon::createFromTimestamp($this->info['subscribe_time']);
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $user = User::firstOrCreate(['open_id' => $this->info['openid']]);

        $user->update([
            'nickname' => $this->info['nickname'],
            'avatar' => $this->info['headimgurl'],
            'subscribed_at' => $this->subscribed_at->toDateTimeString(),
        ]);
    }


    /**
     * 获得关注权重
     *
     * @return float
     */
    public function weight()
    {
        $dt = Carbon::parse(Dictionary::BIRTHDAY);

        $year = $dt->diffInYears($this->subscribed_at);

        if($year > 0){
            return floatval(pow(0.95, $year));
        }else{
            $month = $dt->diffInMonths($this->subscribed_at);

            if($month < 1){
                return 1.3;
            }else if($month < 3){
                return 1.2;
            }else{
                return 1.1;
            }
        }
    }
}
